<?php

class Controller_User_Register extends Controller_Site {

	public function before() {
		parent::before();
		// load config account types
		Config::load('account_types', true);
	}

	public function action_index() {
		// set title
		$this->title('Register Account');
		// set content
		$this->content('user/register/' . $type, array('genders' => Model_Gender::find('all')));
	}

	public function post_index() {
		// submit data
		if (Input::is_ajax()) {
			// check if email address exitst
			if (Model_User::query()->where('email', Input::post('email'))->count() == 1) {
				Lib\Response::json(array('error' => Lib\Message::error('Email is already exists')), true);
			}

			// validate
			$val = Lib\Validate::forge();
			$val->add_fields(static::fields('register'));
			if (!$val->run()) {
				Lib\Response::json(array('alert' => $val->get_errors()), true);
			}

			// check if not agree terms and conditions
			if (Input::post('accept') == 0) {
				Lib\Response::json(array('error' => Lib\Message::error('You must agree our terms and conditions')), true);
			}

			$fields = array_merge(array(
				'created_at' => DB::expr('NOW()'),
				'updated_at' => DB::expr('NOW()'),
				'status' => 'WAITING'
			), $val->validated());
			$fields['username'] = str_replace(array(
				'_',
				'.'
			), '', current(explode('@', $fields['email'])));

			unset($fields['confirm_password']);

			// make password
			$fields['password'] = Helper\Security::hash($fields['password']);

			// save session to go to stage 2
			Session::set('register_fields', $fields);
			// redirect to stage 2
			Session::set('register_type', strtolower($fields['type']));
			Lib\Response::json(array('redirect' => Uri::create('user/register/stage_2')), true);
		}
	}

	public function post_stage_2() {
		// types
		$types = array_keys(Config::get('account_types', array()));
		$type = strtoupper(Session::get('register_type'));

		// submit data
		if (Input::is_ajax()) {
			// check if not type or not exists data submited from stage 1
			if (!in_array($type, $types)) {
				Lib\Response::json(array('alert' => Lib\Message::error('Account type does not exists')));
			}

			if (!Session::get('register_fields')) {
				Lib\Response::json(array('alert' => Lib\Message::error('Time process is too long. Your register is canceled.')));
			}

			// validate
			$val = Lib\Validate::forge();
			$val->add_fields(static::fields(strtolower($type) . '_register'));
			if (!$val->run()) {
				Lib\Response::json(array('alert' => $val->get_errors()), true);
			}

			// get fields data from stage 1
			$fields = Session::get('register_fields');

			// save account
			if (DB::insert('users')->set($fields)->execute()) {
				$user_new_id = Model_User::find('first', array(
					'select' => 'id',
					'limit' => 1,
					'order_by' => array('id' => 'desc')
				))->id;
				// save user meta
				if (method_exists($this, '_' . $type)) {
					call_user_func_array(array(
						$this,
						'_' . $type
					), array(
						$user_new_id,
						$val->validated()
					));
				}

				// insert to cron emails to run cron job
				$fields['activate_code'] = Helper\String::random('alnum', 10);
				$fields['time_activate_expired'] = time() + Config::get('setting.time_activate_expired', 5) * 86400;
				// default 5 days
				DB::insert('cron_emails')->set(array(
					'subject' => 'Thank for your registration',
					'body' => View::forge('user/email_template/success', $fields)->render(),
					'from_email' => Config::get('setting.email_from'),
					'from_name' => Config::get('setting.email_name'),
					'to_email' => $fields['email'],
					'to_name' => ($fields['first_name'] . ' ' . $fields['last_name']),
					'created_at' => DB::expr('NOW()')
				))->execute();

				Session::delete('register_fields');

				Lib\Response::json(array('redirect' => Uri::create('user/register/success')), 1);
			}
		}
	}

	public function action_stage_2() {
		// types
		$types = array_keys(Config::get('account_types', array()));
		$type = Session::get('register_type');
		$type = strtoupper($type);
		// check if not type or not exists data submited from stage 1
		if ( !in_array($type, $types) || !Session::get('register_fields') )
		{
			Response::redirect('login');
		}
		// $type = 'LSP';

		switch ( $type ) {
			case 'DEAF' :
				$communications = array();
				foreach (Model_Communication::find('all') as $s) {
					$communications[$s->id] = $s->name;
				}
				$this->set('communications', $communications);

				$preferences = array();
				foreach (Model_Preference::find('all') as $s) {
					$preferences[$s->id] = $s->name;
				}
				$this->set('preferences', $preferences);
				break;
			case 'BUSINESS' :
				$services = array();
				foreach (Model_Service::find('all') as $s) {
					$services[$s->id] = $s->name;
				}
				$this->set('services', $services);

				$zones = array();
				foreach (Model_Zone::find('all', array('where' => array('country_id' => 1))) as $s) {
					$zones[$s->id . '_' . $s->country_id] = $s->name;
				}
				$this->set('zones', $zones);

				$type_of_business = array();
				foreach (Model_Business_Type::find('all') as $s) {
					$type_of_business[$s->id] = $s->name;
				}
				$this->set('type_of_business', $type_of_business);

				$employees = array();
				for ($i = 1; $i <= 10; $i++) {
					$employees[$i] = $i;
				}
				$this->set('number_of_employees', $employees);
				break;
			case 'LSP' :
				$countries = array();
				foreach (Model_Country::find('all') as $s) {
					$countries[$s->id] = $s->name;
				}
				$this->set('countries', $countries);

				$expertises = array();
				foreach (Model_Expertise::find('all') as $s) {
					$expertises[$s->id] = $s->name;
				}
				$this->set('expertises', $expertises);

				$memberships = array();
				foreach (Model_Membership::find('all') as $s) {
					$memberships[$s->id] = $s->name;
				}
				$this->set('memberships', $memberships);

				$roles = array();
				foreach (Model_Role::find('all') as $s) {
					$roles[$s->id] = $s->name;
				}
				$this->set('roles', $roles);

				$qualifications = array();
				$this->set('qualifications', $qualifications);

				$qualification_types = array();
				foreach(Model_Qualification_Type::find('all') as $s) {
					$qualification_types[$s->id] = $s->name;
				}
				$this->set('qualification_types', $qualification_types);
				break;
		}

		// set title
		$titles = array(
			'DEAF' => 'User Registration',
			'LSP' => 'LSP Registration',
			'BUSINESS' => 'Business Registration'
		);
		$this->title($titles[$type]);

		$countries = array();
		foreach (Model_Country::find('all') as $s) {
			$countries[$s->id] = $s->name;
		}
		$this->set('countries', $countries);

		// set content
		$this->content('user/register/' . strtolower($type));
	}

	public function action_success() {
		$this->title('Register successully');
	}

	public function get_qualification($type_id = 0) {
		if($type_id) {
			$qualifications = Model_Qualification::find('all', array(
				'where' => array(
					array('type_id', $type_id)
				)
			));

			$output = array(
				'status' => true,
				'html' => ''
			);
			foreach($qualifications as $a) {
				$output['html'] .= '<option value="'.$a->id.'">'.$a->name.'</option>';
			}

			Lib\Response::json($output);
		}
	}

	private static function fields($type = '') {
		switch ( $type ) {
			case 'register' :
				$fields = array(
					'gender' => array(
						'label' => 'Title',
						'validate' => 'required'
					),
					'first_name' => array(
						'label' => 'First name',
						'validate' => 'required'
					),
					'last_name' => array(
						'label' => 'Last name',
						'validate' => 'required'
					),
					'email' => array(
						'label' => 'Email',
						'validate' => 'required|valid_email'
					),
					'password' => array(
						'label' => 'Password',
						'validate' => 'required|min_length[6]'
					),
					'confirm_password' => array(
						'label' => 'Confirm password',
						'validate' => 'match_field[password]'
					),
					'type' => array(
						'label' => 'Account type',
						'validate' => 'required'
					),
					'security_question' => array(
						'label' => 'Security Question',
						'validate' => 'required'
					),
					'security_answer' => array(
						'label' => 'Security Answer',
						'validate' => 'required'
					),
					'has_newsletter' => array(
						'label' => 'Has newsletter',
						'validate' => 'required'
					)
				);
				break;

			case 'business_register' :
				$fields = array(
					'position' => array(
						'label' => 'Position',
						'validate' => 'required'
					),
					'company_name' => array(
						'label' => 'Company name',
						'validate' => 'required'
					),
					'company_registration_no' => array(
						'label' => 'Company registration No',
						'validate' => 'required'
					),
					'company_mobile_no' => array(
						'label' => 'Company mobile No',
						'validate' => 'required'
					),
					'company_address' => array(
						'label' => 'Company address',
						'validate' => 'required'
					),
					'country_id' => array(
						'label' => 'Country',
						'validate' => 'required'
					),
					'post_code' => array(
						'label' => 'Post code',
						'validate' => 'required'
					),
					'type_business_id' => array(
						'label' => 'Type of business'
					),
					'service_ids' => array(
						'label' => 'Company registration No'
					),
					'number_of_employees' => array(
						'label' => 'Number of employees'
					),
					'company_work_ids' => array(
						'label' => 'Regions work'
					)
				);
				break;

			case 'lsp_register' :
				$fields = array(
					'mobile_number' => array(
						'label' => 'Mobile Number',
						'validate' => 'required'
					),
					'work_address' => array(
						'label' => 'Work Address',
						'validate' => 'required'
					),
					'work_address_1' => array(
						'label' => 'Work Address 2',
						'validate' => 'required'
					),
					'work_address_2' => array(
						'label' => 'Work Address 3',
						'validate' => 'required'
					),
					'country_id' => array(
						'label' => 'Country',
						'validate' => 'required'
					),
					'post_code' => array(
						'label' => 'Post code',
						'validate' => 'required'
					),
					'nrcpd_no' => array(),
					'membership_id' => array(),
					'membership_date_joined' => array(),
					'qualification_type_id' => array(),
					'expertise_date_start' => array(),
					'expertise_id' => array(),
					'qualification_id' => array(),					
					'qualification_date_archived' => array(),					
					'region_id' => array(),
					'roles' => array()
				);
				break;

			case 'deaf_register' :
				$fields = array(
					'mobile_number' => array(
						'label' => 'Mobile Number',
						'validate' => 'required'
					),
					'home_address' => array(
						'label' => 'Home Address',
						'validate' => 'required'
					),
					'home_address_1' => array(
						'label' => 'Home Address 1',
						'validate' => 'required'
					),
					'home_address_2' => array(
						'label' => 'Home Address 2',
						'validate' => 'required'
					),
					'country_id' => array(
						'label' => 'Country',
						'validate' => 'required'
					),
					'post_code' => array(
						'label' => 'Postcode',
						'validate' => 'required',
						'messages' => array('required' => '<strong>:label</strong> must be enter')
					),
					'communication_id' => array(
						'validate' => 'required',
						'messages' => array('required' => 'Please choose at least one communication')
					),
					'communication_support_id' => array(
						'validate' => 'required',
						'messages' => array('required' => 'Please choose at least one communication support')
					),
					'second_preference_id' => array(
						'validate' => 'required',
						'messages' => array('required' => 'Please choose at least one second preference')
					)
				);
				break;

			default :
				$fields = array();
				break;
		}

		return $fields;
	}

	private function _deaf($user_id, $fields = array ()) {
		$fields['user_id'] = $user_id;
		return DB::insert('user_deaf')->set($fields)->execute();
	}

	private function _lsp($user_id, $fields = array ()) {
		// lsp user
		DB::insert('user_lsp')
		->set(array(
			'user_id' => $user_id,
			'mobile_number' => $fields['mobile_number'],
			'work_address' => $fields['work_address'],
			'work_address_1' => $fields['work_address_1'],
			'work_address_2' => $fields['work_address_2'],
			'country_id' => $fields['country_id'],
			'post_code' => $fields['post_code'],
		))
		->execute();

		// expertises
		if(isset($fields['expertise_id']) AND count($fields['expertise_id'])) {
			foreach($fields['expertise_id'] as $key => $val) {
				DB::insert('user_lsp_expertises')
				->set(array(
					'user_id' => $user_id,
					'expertise_id' => $val,
					'date_start' => $fields['expertise_date_start'][$key]
				))
				->execute();
			}
		}

		// memberships
		if(isset($fields['membership_id']) AND count($fields['membership_id'])) {
			foreach($fields['membership_id'] as $key => $val) {
				DB::insert('user_lsp_memberships')
				->set(array(
					'user_id' => $user_id,
					'membership_id' => $val,
					'date_join' => $fields['membership_date_joined'][$key]
				))
				->execute();
			}
		}

		// nrcpd
		if(isset($fields['nrcpd_no']) AND count($fields['nrcpd_no'])) {
			foreach($fields['nrcpd_no'] as $key => $val) {
				DB::insert('user_lsp_nrcpd')
					->set(array(
						'user_id' => $user_id,
						'nrcpd_no' => $val
					))
					->execute();
			}
		}

		// qualifications
		if(isset($fields['qualification_type_id']) AND count($fields['qualification_type_id'])) {
			foreach($fields['qualification_type_id'] as $key => $val) {
				DB::insert('user_lsp_qualifications')
				->set(array(
					'user_id' => $user_id,
					'type_id' => $val,
					'qualification_id' => $fields['qualification_id'][$key],
					'date_archive' => $fields['qualification_date_archived'][$key]
				))
				->execute();
			}
		}

		// roles
		if(isset($fields['roles']) AND count($fields['roles'])) {
			foreach($fields['roles'] as $val) {
				DB::insert('user_lsp_roles')
				->set(array(
					'user_id' => $user_id,
					'role_id' => $val
				))
				->execute();
			}
		}

		// work at
		if(isset($fields['region_id']) AND count($fields['region_id'])) {
			foreach($fields['region_id'] as $val) {
				DB::insert('user_lsp_work_at')
				->set(array(
					'user_id' => $user_id,
					'country_id' => $val
				))
				->execute();
			}
		}
	}

	private function _business($user_id, $fields = array ()) {
		$service_ids = $fields['service_ids'];
		unset($fields['service_ids']);
		$region_ids = $fields['company_work_ids'];
		unset($fields['company_work_ids']);

		$fields['user_id'] = $user_id;
		DB::insert('user_business')->set($fields)->execute();
		// services
		if (count($service_ids)) {
			foreach ($service_ids as $id) {
				DB::insert('user_business_services')->set(array(
					'user_id' => $user_id,
					'service_id' => $id
				))->execute();
			}
		}

		// regions work
		if (count($region_ids)) {
			foreach ($region_ids as $id) {
				list($country_id, $zone_id) = explode('_', $id);
				DB::insert('user_business_work_at')->set(array(
					'user_id' => $user_id,
					'country_id' => $country_id,
					'zone_id' => $zone_id
				))->execute();
			}
		}

	}

}
